<?php
declare (strict_types = 1);

namespace app\middleware;

use app\msgapi\model\{AdminUser, AuthRule, AuthGroup};
use app\utils\Arr;

class MsgApiHttp
{
    private AdminUser $adminUser;
    private AuthRule $authRule;
    private AuthGroup $authGroup;
    public function __construct(AdminUser $adminUser, AuthRule $authRule, AuthGroup $authGroup)
    {
        $this->adminUser = $adminUser;
        $this->authRule = $authRule;
        $this->authGroup = $authGroup;
    }

    /**
     * 访问权限检查
     * @param $request
     * @param \Closure $next
     * @return mixed|\think\response\Json|\think\response\Redirect
     */
    public function handle($request, \Closure $next)
    {
        // 再次检查用户状态
        if(!$this->checkState($request->adminid)){
            return error_json('用户已被禁用');
        }
        // 检测url权限
        $groupId = $request->admin_groupid;
        if ($groupId > 1 && !$this->checkUrl($request->controller() . '/' . $request->action(), $groupId)){
            return error_json('没有此权限', [], -101);
        }
        return $next($request);
    }

    /**
     * 检测用户组是否具备访问url的权限
     * @param string $url   url，控制器/方法
     * @param int $groupId 当前用户组
     * @return bool
     */
    private function checkUrl(string $url, int $groupId): bool
    {
        // 当前用户组已授权的url列表
        $authList = $this->authRule->where('id', 'in', $this->authGroup->getRulesShow($groupId))->column('url');
        // 所有的url列表
        $authListAll = $this->authRule->column('url');
        // 仅当前操作存在auth_rule表中，但不存在授权的列表中authList时无权限
        if(Arr::inArrayCI($url, $authListAll) && !Arr::inArrayCI($url, $authList)){
            return false;
        }
        return true;
    }

    /**
     * 根据id返回此用户状态，禁用时返回false
     * @param int $id   用户id
     * @return bool
     */
    private function checkState(int $id): bool
    {
        if($this->adminUser->getStateById($id) != 1){
            return false;
        }
        return true;
    }
}
